package com.hoshiicloud.shxping.jobhandler;

import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.DateUtil;
import com.hoshiicloud.saleorder.dto.OrderDTO;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.param.OrderQueryParam;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yangcheng
 * @version 1.0
 * @title: AutoCancelOrderHandler
 * @description: 自动取消订单定时任务
 * @date 2019/9/3 11:28
 * @mail maiboyc@163.com
 */
@JobHandler("autoCancelOrderHandler")
@Component
public class AutoCancelOrderHandler extends IJobHandler {

    // 订单微服务Service
    @Autowired
    private OrderFeignService orderFeignService;

    // 任务执行
    @Override
    public ReturnT<String> execute(String s){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            XxlJobLogger.log("自动取消订单任务begin----", System.currentTimeMillis());
            //查询待付款订单
            OrderQueryParam param = new OrderQueryParam();
            param.setStatus(2);
            Response<List<OrderDTO>> response = orderFeignService.listAllOrders(param);
            if (response != null && response.getData() != null && response.getData().size() > 0) {
                //主订单id
                List<Long> orderIds = new ArrayList<>();
                for (OrderDTO orderDTO : response.getData()) {
                    Long mins = DateUtil.differentMinsByMillisecond(LocalDateTime.parse(orderDTO.getCreateTime(),df), LocalDateTime.now());
                    // 下单时间超过30分钟
                    if (mins > 30) {
                        orderIds.add(orderDTO.getOrderId());
                    }
                }
                if (orderIds.size() > 0) {
                    //批量取消订单
                    orderFeignService.batchCancelOrder(orderIds);
                }
            }
            XxlJobLogger.log("自动取消订单任务end----");
        } catch (Exception e) {
            XxlJobLogger.log("自动取消订单任务异常：", e);
        }
        return SUCCESS;
    }
}
